package com.lst.demo.ui;


import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AlphabetIndexer;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.andrognito.patternlockview.PatternLockView;
import com.andrognito.patternlockview.listener.PatternLockViewListener;
import com.andrognito.patternlockview.utils.PatternLockUtils;
import com.andrognito.patternlockview.utils.ResourceUtils;
import com.andrognito.rxpatternlockview.RxPatternLockView;
import com.andrognito.rxpatternlockview.events.PatternLockCompleteEvent;
import com.andrognito.rxpatternlockview.events.PatternLockCompoundEvent;
import com.blankj.utilcode.util.SPUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.lst.demo.R;

import java.util.List;

import io.reactivex.functions.Consumer;

public class UnLockActivity extends AppCompatActivity {

    private PatternLockView mPatternLockView;
    private TextView tvProfileName;
    private TextView tvProfileInfo;
    private LinearLayout llBottom;

    @SuppressLint("CheckResult")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_set_lock_view);

        ImmersionBar.with(this)
                .fitsSystemWindows(true)
                .statusBarColor(R.color.white)//设置状态栏颜色为白色
                .statusBarDarkFont(true, 0.2f) //原理：如果当前设备支持状态栏字体变色，会设置状态栏字体为黑色，如果当前设备不支持状态栏字体变色，会使当前状态栏加上透明度，否则不执行透明度
                .navigationBarColor(R.color.white)
                .navigationBarDarkIcon(true)
                .init();

        //获取控件对象
        mPatternLockView = (PatternLockView) findViewById(R.id.patter_lock_view);

        tvProfileName = findViewById(R.id.profile_name);

        tvProfileInfo = findViewById(R.id.profile_info);

        llBottom = findViewById(R.id.ll_bottom);

        tvProfileName.setText("请绘制解锁图案");
        tvProfileInfo.setVisibility(View.INVISIBLE);

        findViewById(R.id.img_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                finish();
            }
        });


        // mPatternLockView.setViewMode(PatternLockView.PatternViewMode.CORRECT);       // 设置当前视图更多
//        mPatternLockView.setInStealthMode(true);                                     // 将模式设置为隐藏模式（隐藏模式绘图）
        mPatternLockView.setTactileFeedbackEnabled(true);                            //绘制图案时启用振动反馈

        mPatternLockView.setCorrectStateColor(Color.parseColor("#00ff00"));//设置解锁成功颜色为绿色

//        mPatternLockView.setInputEnabled(false);                                     //完全禁用模式锁定视图中的任何输入
//        mPatternLockView.setDotCount(3);
//        mPatternLockView.setDotNormalSize((int) ResourceUtils.getDimensionInPx(this, R.dimen.pattern_lock_dot_size));
//        mPatternLockView.setDotSelectedSize((int) ResourceUtils.getDimensionInPx(this, R.dimen.pattern_lock_dot_selected_size));
//        mPatternLockView.setPathWidth((int) ResourceUtils.getDimensionInPx(this, R.dimen.pattern_lock_path_width));
//        mPatternLockView.setAspectRatioEnabled(true);
//        mPatternLockView.setAspectRatio(PatternLockView.AspectRatio.ASPECT_RATIO_HEIGHT_BIAS);
//        mPatternLockView.setNormalStateColor(ResourceUtils.getColor(this, R.color.white));
//        mPatternLockView.setCorrectStateColor(ResourceUtils.getColor(this, R.color.primary));
//        mPatternLockView.setWrongStateColor(ResourceUtils.getColor(this, R.color.pomegranate));
//        mPatternLockView.setDotAnimationDuration(150);
//        mPatternLockView.setPathEndAnimationDuration(100);


        // n*n大小   3*3
        mPatternLockView.setDotCount(3);
        //没有点击时点的大小
      //  mPatternLockView.setDotNormalSize((int) ResourceUtils.getDimensionInPx(this, R.dimen.pattern_lock_dot_size));
        //点击时点的大小
      //  mPatternLockView.setDotSelectedSize((int) ResourceUtils.getDimensionInPx(this, R.dimen.pattern_lock_dot_selected_size));
        //更改路径距离
      //  mPatternLockView.setPathWidth((int) ResourceUtils.getDimensionInPx(this, R.dimen.pattern_lock_path_width));
        mPatternLockView.setAspectRatioEnabled(true);
        mPatternLockView.setAspectRatio(PatternLockView.AspectRatio.ASPECT_RATIO_HEIGHT_BIAS);
        //mPatternLockView.setViewMode(PatternLockView.PatternViewMode.CORRECT);
        mPatternLockView.setDotAnimationDuration(150);
        mPatternLockView.setPathEndAnimationDuration(100);
        mPatternLockView.setInStealthMode(false);
        mPatternLockView.setTactileFeedbackEnabled(true);
        mPatternLockView.setInputEnabled(true);
        mPatternLockView.addPatternLockListener(mPatternLockViewListener);


        RxPatternLockView.patternComplete(mPatternLockView)
                .subscribe(new Consumer<PatternLockCompleteEvent>() {
                    @Override
                    public void accept(PatternLockCompleteEvent patternLockCompleteEvent) throws Exception {
                        Log.d(getClass().getName(), "Complete: " + patternLockCompleteEvent.getPattern().toString());
                    }
                });

        RxPatternLockView.patternChanges(mPatternLockView)
                .subscribe(new Consumer<PatternLockCompoundEvent>() {
                    @Override
                    public void accept(PatternLockCompoundEvent event) throws Exception {
                        if (event.getEventType() == PatternLockCompoundEvent.EventType.PATTERN_STARTED) {
                            Log.d(getClass().getName(), "Pattern drawing started");
                        } else if (event.getEventType() == PatternLockCompoundEvent.EventType.PATTERN_PROGRESS) {
                            Log.d(getClass().getName(), "Pattern progress: " +
                                    PatternLockUtils.patternToString(mPatternLockView, event.getPattern()));
                        } else if (event.getEventType() == PatternLockCompoundEvent.EventType.PATTERN_COMPLETE) {
                            Log.d(getClass().getName(), "Pattern complete: " +
                                    PatternLockUtils.patternToString(mPatternLockView, event.getPattern()));
                        } else if (event.getEventType() == PatternLockCompoundEvent.EventType.PATTERN_CLEARED) {
                            Log.d(getClass().getName(), "Pattern has been cleared");
                        }
                    }
                });

    }

    private int count = 5;

    //设置监听器
    private PatternLockViewListener mPatternLockViewListener = new PatternLockViewListener() {
        @Override
        public void onStarted() {
            Log.d(getClass().getName(), "Pattern drawing started");
        }

        @Override
        public void onProgress(List<PatternLockView.Dot> progressPattern) {
            Log.d(getClass().getName(), "Pattern progress: " +
                    PatternLockUtils.patternToString(mPatternLockView, progressPattern));
        }

        @Override
        public void onComplete(List<PatternLockView.Dot> pattern) {
            Log.d(getClass().getName(), "Pattern complete: " +
                    PatternLockUtils.patternToString(mPatternLockView, pattern));

//            mPatternLockView.setViewMode(PatternLockView.PatternViewMode.AUTO_DRAW);


            //密码
            String patternToString = PatternLockUtils.patternToString(mPatternLockView, pattern);
            if (!TextUtils.isEmpty(patternToString)) {


                String lockpaswd = SPUtils.getInstance().getString("lockpaswd");
                if (patternToString.equals(lockpaswd)) {
                    mPatternLockView.setViewMode(PatternLockView.PatternViewMode.CORRECT);
                    mPatternLockView.setEnabled(false);
                    tvProfileName.setText("解锁成功");
                    tvProfileInfo.setVisibility(View.INVISIBLE);
                } else {

                    count--;

                    //密码错误
                    mPatternLockView.setViewMode(PatternLockView.PatternViewMode.WRONG);
                    tvProfileInfo.setVisibility(View.VISIBLE);
                    tvProfileInfo.setTextColor(Color.parseColor("#ff0000"));
                    if (count > 0) {

                        tvProfileInfo.setText("密码错误,还可以再输入" + count + "次");
                        //1s后清除图案
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mPatternLockView.clearPattern();
                            }
                        }, 1000);
                    } else {
                        tvProfileInfo.setText("已达到解锁次数限制,请使用密码登录");
                        showDialog();
                        //解锁次数达到限制之后,禁止绘制
                        mPatternLockView.setEnabled(false);
                    }

                }


            }


        }

        @Override
        public void onCleared() {
            Log.d(getClass().getName(), "Pattern has been cleared");
        }
    };


    private void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(false);
        builder.setTitle("提示");
        builder.setMessage("已达到解锁次数限制，请使用密码登录");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                finish();
            }
        });
//        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
//
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                dialog.dismiss();
//                finish();
//            }
//        });
        AlertDialog mAlertDialog = builder.create();
        mAlertDialog.show();

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        SPUtils.getInstance().remove("firstlockpaswd");
        SPUtils.getInstance().remove("confirmlockpaswd");

    }
}